%% @author Rain
%% @doc 基础接口


-module(util).

-include("global.hrl").

%% ====================================================================
%% API functions
%% ====================================================================
-export([to_integer/1,
		 to_atom/1,
		 to_list/1,
		 reload_all_ebin/0,
		 make_proto/0,
		 make_proto/1]).

%% ====================================================================
%% Internal functions
%% ====================================================================


%% @doc 将不同类型的数据转换为整数
to_integer(Atom) when is_atom(Atom) ->
	list_to_integer(atom_to_list(Atom));
to_integer(List) when is_list(List) ->
	list_to_integer(List);
to_integer(Binary) when is_binary(Binary) ->
	list_to_integer(binary_to_list(Binary)).

%% @doc 将不同类型的数据转换为原子
to_atom(List) when is_list(List) ->
	list_to_atom(List);
to_atom(Int) when is_integer(Int) ->
	List = integer_to_list(Int),
	list_to_atom(List);
to_atom(Binary) when is_binary(Binary) ->
	binary_to_atom(Binary);
to_atom(Any) ->
	Any.

%% @doc 将不同类型的数据转换为列表
to_list(Int) when is_integer(Int) ->
	integer_to_list(Int);
to_list(Binary) when is_binary(Binary) ->
	binary_to_list(Binary);
to_list(Atom) when is_atom(Atom) ->
	atom_to_list(Atom);
to_list(Any) ->
	Any.

%% @doc 导出单个协议
make_proto(ProtoId) when is_atom(ProtoId) ->
	FileName = "./proto/"++atom_to_list(ProtoId)++".proto",
	io:format("===========make proto ~p begin=================~n", [ProtoId]),
	io:format("======FileName ~p==========~n", [FileName]),
	gpb_compile:c(?PROTO_OPT, [FileName]),
	io:format("===========make proto ~p end=================~n", [ProtoId]);
make_proto(_) ->
	io:format("[ERROR] Input Is Not An Atom").

%% @doc 导出全部协议
make_proto() ->
	io:format("===========make all proto begin=================~n"),
	FileNameList = all_proto_file(),
	gpb_compile:c(?PROTO_OPT, FileNameList),
	io:format("===========make all proto end=================~n").

%% @doc 获取所有proto文件（包含路径）
all_proto_file() ->
	LogicNames = filelib:wildcard(?ALL_PROTO_PATH++"*.proto"),
	LogicNames.


%% @doc 获取所有beam文件（包含路径）
all_ebin_file() ->
	LogicNames = filelib:wildcard(?ALL_EBIN_PATH++"*.beam"),
	LogicNames.

%% @doc 重载所有beam文件
reload_all_ebin() ->
	io:format("-----------------------------------------------~n"),
	io:format("reload_all_ebin ~n~n", []),
	F = fun(FilePath) ->
				Module = list_to_atom(filename:basename(FilePath, ".beam")),
				c:l(Module),
				io:format("~w:load ~w ok~n", [calendar:local_time(), Module])
		end,
	lists:foreach(F, all_ebin_file()),
	io:format("~n"),
	io:format("-----------------------------------------------~n").


